<template>
    <div>
        <van-form>
            <van-field label='手机号' v-model="mobile" :rules="[{'required':true,'message':'手机号不能为空'}]"/>
            <van-button @click="send" color="linear-gradient(to left, yellow,red)" :disabled="disabled">{{mes}}</van-button>
            <van-field label='验证码' v-model="code" :rules="[{'required':true,'message':'验证码不能为空'}]"/>
            <van-button color="linear-gradient(to left, blue,pink)" @click="login">登录</van-button>
        </van-form>
    </div>
</template>

<script>
    export default {
        data(){
            return{
                mes:'发送验证码',
                mobile:'',
                code:'',
                time:60,
                disabled:false
            }
        },
        methods:{
            send(){
                if(this.mobile==''){
                    alert('手机号不能为空')
                }
                let reg = /^1[3-9]\d{9}$/
                if(!reg.test(this.mobile)){
                    alert('手机号不合法')
                    return false
                }
                this.smscode()
            },
            smscode(){
                this.$axios.get('sendsms?mobile='+this.mobile).then(res=>{
                    if(res.data.code==200){
                        let m = setInterval(()=>{
                            this.time--
                            this.disabled=true
                            this.mes = this.time + '后重新获取验证码'
                        if(this.time==0){
                            clearInterval(m)
                            this.time=60
                            this.disabled=false
                            this.mes='发送验证码'
                        }
                        },1000)
                    }else{
                        alert(res.data.mes)
                        return false;
                    }
                })
            },
            login(){
                this.$axios.post('login',{'mobile':this.mobile,'code':this.code}).then(res=>{
                    if(res.data.code==200){
                        alert('登陆成功')
                        localStorage.setItem('id',res.data.user.id)
                        localStorage.setItem('mobile',res.data.user.name)
                        localStorage.setItem('token',res.data.token)
                        localStorage.setItem('newtoken',res.data.newtoken)
                        localStorage.setItem('reslist',JSON.stringify(res.data.reslist))
                        this.$router.push('/index')
                    }else{
                        alert(res.data.mes)
                    }
                })
            }
        }
    }
</script>

<style scoped>

</style>